package com.viewpagertext.activitys;

import static com.viewpagertext.service.MusicService.mediaPlayer;
import static com.viewpagertext.app.ScrollShapeUIApplication.context;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;

import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.core.view.GravityCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.widget.Toolbar;

import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.makeramen.roundedimageview.RoundedImageView;
import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.PlaybackModeDao;
import com.viewpagertext.DBHelper.Dao.StarredSongDao;
import com.viewpagertext.Model.UpdateUIEvent;
import com.viewpagertext.constructor.ListToPlayEvent;
import com.viewpagertext.json.PlaybackMode;
import com.viewpagertext.service.MusicService;
import com.viewpagertext.R;
import com.viewpagertext.adapters.HomeFragmentStatePagerAdapter;
import com.viewpagertext.fragments.FindFragment;
import com.viewpagertext.fragments.FriendFragment;
import com.viewpagertext.fragments.MyFragment;
import com.viewpagertext.json.StarredSong;
import com.viewpagertext.utils.PermissionUtils;
import com.viewpagertext.utils.StatusBarUtil;
import com.viewpagertext.utils.TimeUtil;
import com.viewpagertext.utils.UserUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;




public class MainActivity extends AppCompatActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {
    private MusicService.MusicBinder musicBinder;
    public static String Username = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 123;

    /**
     * 歌曲列表
     */
    public static List<StarredSong> mList = new ArrayList<>();
    public static int playPosition = 0;
    //底部栏
    RoundedImageView roundedImageViewPause;
    RoundedImageView roundedImageViewNext;
    RoundedImageView roundedImageViewPrev;
    RoundedImageView MainButtomPic;
    LinearLayout seeSong;
    public static String nowMode;
    public static MusicService musicService;
    private DrawerLayout mDrawerLayout;
    StarredSongDao helper = AppDatabase.getInstance().starredSongDao();
    private Toolbar toolbar;
    private ViewPager viewPager;
    private HomeFragmentStatePagerAdapter myFragmentStatePagerAdapter;
    private List<Fragment> mDatas;
    public static TextView btn_song_name;
    private TextView tv_my, tv_find, tv_friends, nav_close, username, btn_singer;
    private ServiceConnection connection = new ServiceConnection() {

        /**
         * 连接服务
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder = (MusicService.MusicBinder) service;
            musicService = musicBinder.getService();

            System.out.println("Service与Activity已连接");

        }

        //断开服务
        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicBinder = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setTransparentForImageView(this, toolbar);
        StatusBarUtil.StatusBarTextColor(this, true);
        EventBus.getDefault().register(this);//注册消息
        initData();//添加Fragment到 List<Fragment> mDatas集合
        initIdListener();//获取控件实例
        header_click();//动态加载nav头布局
        StatusBarUtil.statusBarVersion(this);
        PermissionUtils.initCheckSelfPermission(this);
        myFragmentStatePagerAdapter = new HomeFragmentStatePagerAdapter(getSupportFragmentManager(), mDatas);
        viewPager.setAdapter(myFragmentStatePagerAdapter);
        viewPager.setCurrentItem(1);//默认首次进入的页面
        setTitleTextViewColor(viewPager.getCurrentItem());//首次加载viewPager 页面对应的button的文字颜色
        PlaybackModeDao playbackModeHelper = AppDatabase.getInstance().playbackModeDao();
        nowMode = playbackModeHelper.getCurrentPlaybackMode(); // 读取当前播放模式

        //获取权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 权限未被授予
            System.out.println("权限违背授予");
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                // 应该显示一个对话框给用户解释为什么需要这个权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    // 显示解释对话框
                } else {
                    // 直接请求权限
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                }
            }

        }

    }

    //    private void requestManagerPermission() {
//        //当系统在11及以上
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//            // 没文件管理权限时申请权限
//            if (!Environment.isExternalStorageManager()) {
//                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
//                intent.setData(Uri.parse("package:" + mContext.getPackageName()));
//                startActivityForResult(intent, REQUEST_MANAGER_PERMISSION);
//            }
//        }
//    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    showDialog();
                }
                break;
        }
    }

    private void showDialog() {
        Dialog dialog = new AlertDialog.Builder(this)
                .setMessage("请授权必要权限")
                .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        PermissionUtils.initCheckSelfPermission(MainActivity.this);
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失
        dialog.setCancelable(false);//点击返回键不消失
        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 当Activity恢复时触发事件
        if (Username.isEmpty()) username.setText("点击登录");
        else username.setText(Username);
    }

    /**
     * 发现页面的事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_my:
                viewPager.setCurrentItem(0);
                break;
            case R.id.tv_find:
                viewPager.setCurrentItem(1);
                break;
            case R.id.tv_friends:
                viewPager.setCurrentItem(2);
                break;
            case R.id.nav_close:
                System.exit(0);
                break;
            case R.id.username:
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    //nav布局Item点击项
    private void header_click() {
        NavigationView navigationView = findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.AppHome:
                        Intent intent = new Intent(MainActivity.this, ProjectHomeActivity.class);
                        startActivity(intent);
                }

                return true;
            }
        });


        View nav_header = navigationView.inflateHeaderView(R.layout.nav_header);
        username = nav_header.findViewById(R.id.username);
        username.setOnClickListener(this);


        //给底部栏添加点击事件
        roundedImageViewPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理点击事件
                System.out.println("界面内开始");
                musicService.pauseOrContinueMusic();

            }
        });

        roundedImageViewNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理点击事件
                System.out.println("界面内点击下一首");
                musicService.nextMusic();
            }
        });

        roundedImageViewPrev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理点击事件
                musicService.previousMusic();

            }
        });

        seeSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理点击事件
                Intent intent = new Intent(MainActivity.this, SongActivity.class);
//                    viewPager.setCurrentItem(1);
                EventBus.getDefault().postSticky(new ListToPlayEvent(mList.get(playPosition).getPic(), mList.get(playPosition).getName(),
                        mList.get(playPosition).getSinger(), mList.get(playPosition).getLrc(),
                        mList.get(playPosition).getUrl(), TimeUtil.formatSeconds(mList.get(playPosition).getTime()),
                        mList.get(playPosition).getSongId()));
                startActivity(intent);
                Toast.makeText(MainActivity.this, "跳转到音乐界面", Toast.LENGTH_SHORT).show();
            }
        });

    }


    /**
     * 获取控件实例
     */
    private void initIdListener() {
        //toolbar
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        //抽屉布局
        mDrawerLayout = findViewById(R.id.drawer_layout);
        viewPager = findViewById(R.id.viewPager);

        //toolbar_TextView
        tv_my = findViewById(R.id.tv_my);
        tv_find = findViewById(R.id.tv_find);
        tv_friends = findViewById(R.id.tv_friends);
        viewPager.setOnPageChangeListener(this);
        tv_my.setOnClickListener(this);
        tv_find.setOnClickListener(this);
        tv_friends.setOnClickListener(this);

        //nav的退出
        nav_close = findViewById(R.id.nav_close);
        nav_close.setOnClickListener(this);

        btn_song_name = findViewById(R.id.btn_song_name);
        btn_singer = findViewById(R.id.btn_singer);

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);

        roundedImageViewPause = findViewById(R.id.pause);
        roundedImageViewNext = findViewById(R.id.next);
        roundedImageViewPrev = findViewById(R.id.last);
        MainButtomPic = findViewById(R.id.MainButtomPic);//Main底部图片动画
        seeSong = findViewById(R.id.seeSong);


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Animation rotateAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.main_bottom_pic_rotate);
                rotateAnimation.setInterpolator(new LinearInterpolator());
                MainButtomPic.startAnimation(rotateAnimation);
            }
        }).start();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }


    /**
     * Toolbar子项菜单点击事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search:
                Toast.makeText(this, "搜索", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(this, SearchActivity.class);

                this.startActivity(intent);
                break;
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            default:
                break;
        }
        return true;
    }


    /**
     * 添加Fragment到 List<Fragment> mDatas集合
     */
    private void initData() {
        mDatas = new ArrayList<>();
        mDatas.add(new MyFragment());
        mDatas.add(new FindFragment());
        mDatas.add(new FriendFragment());
        //绑定服务
        Intent serviceIntent = new Intent(context, MusicService.class);
        bindService(serviceIntent, connection, BIND_AUTO_CREATE);


        mList = helper.getAllStarredSongs();
        if (mList.size() == 0) {
            Toast.makeText(MainActivity.this, "没有收藏的音乐", Toast.LENGTH_SHORT).show();
        } else {
            playPosition = mList.size() - 1;
        }
    }

    /**
     * 设置字体属性
     */
    private void setTexAttr() {
        UserUtils.setTextColor(tv_my, this, R.color.gray);//设置字体颜色
        UserUtils.setTextColor(tv_find, this, R.color.gray);
        UserUtils.setTextColor(tv_friends, this, R.color.gray);
        UserUtils.setTextSize(tv_my, 16);//设置字体大小
        UserUtils.setTextSize(tv_find, 16);
        UserUtils.setTextSize(tv_friends, 16);
        UserUtils.setTypeface(tv_my, Typeface.NORMAL);//取消加粗
        UserUtils.setTypeface(tv_find, Typeface.NORMAL);
        UserUtils.setTypeface(tv_friends, Typeface.NORMAL);
    }


    /**
     * 设置titleTextView的颜色状态
     *
     * @param currentItem
     */
    private void setTitleTextViewColor(int currentItem) {
        setTexAttr();
        switch (currentItem) {
            case 0:
                UserUtils.setTextColor(tv_my, this, R.color.black);
                UserUtils.setTypeface(tv_my, Typeface.BOLD);
                UserUtils.setTextSize(tv_my, 18);
                break;
            case 1:
                UserUtils.setTextColor(tv_find, this, R.color.black);
                UserUtils.setTypeface(tv_find, Typeface.BOLD);
                UserUtils.setTextSize(tv_find, 18);
                break;
            case 2:
                UserUtils.setTextColor(tv_friends, this, R.color.black);
                UserUtils.setTypeface(tv_friends, Typeface.BOLD);
                UserUtils.setTextSize(tv_friends, 18);
                break;

        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {
    }

    @Override
    public void onPageSelected(int i) {
        setTitleTextViewColor(i);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册
        unbindService(connection);
        System.exit(0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        PermissionUtils.initCheckSelfPermission(this);
    }

    @SuppressLint("SuspiciousIndentation")
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onMessageEvent(UpdateUIEvent event) {
        System.out.println("收到更新UI信息");
        // 更新UI
        if (event.getType() == 1) {
            //播放但是改变歌名
            if (mediaPlayer.isPlaying()) {
                roundedImageViewPause.setImageResource(R.drawable.pause_black);
            } else {
                roundedImageViewPause.setImageResource(R.drawable.play_black);
            }
            btn_song_name.setText(event.getName());
            btn_singer.setText(event.getSinger());
            Glide.with(context)
                    .load(event.getImageUrl())
                    .into(MainButtomPic);
            Animation rotateAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.main_bottom_pic_rotate);
            rotateAnimation.setInterpolator(new LinearInterpolator());
            MainButtomPic.startAnimation(rotateAnimation);

            ImageView imageView = findViewById(R.id.iv_album_cover);
            if (imageView != null)
                Glide.with(context)
                        .load(event.getImageUrl())
                        .into(imageView);
        }

    }


}